const args = require("minimist")(process.argv.slice(2)); // 获取命令行参数
const esbuild = require("esbuild");
const { resolve } = require("path"); // 路径解析

const target = args._[0] || "reactivity"; // 获取目标字符串
const format = args.f || "global"; // 获取格式化方式

const pkg = require(resolve(__dirname, `../packages/${target}/package.json`)); // 获取目标包的package.json文件

// 输出格式  iife: 立即执行函数  cjs: commonJs  esm: esModule
const outputFormat = format.startsWith("global") ? "iife" : format === "cjs" ? "cjs" : "esm";

// 输出文件路径
const outFile = resolve(__dirname, `../packages/${target}/dist/${target}.${format}.js`);

esbuild
  .context({
    entryPoints: [resolve(__dirname, `../packages/${target}/src/index.ts`)],
    outfile: outFile,
    bundle: true,
    sourcemap: true,
    format: outputFormat,
    globalName: pkg.buildOptions?.name,
    platform: format === "cjs" ? "node" : "browser",
    define: {
      __VERSION__: `"${pkg.version}"`,
      __DEV__: `true`,
    },
  })
  .then((ctx) => {
    console.log("🎉 Build succeeded!");
    ctx.watch().then(() => {
      console.log("👀 watching...");
    });
  })
  .catch((err) => {
    console.error("🚫 Build failed:", err);
  });
